#include "Configuration.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <algorithm>

Colors Configuration::playerColors = createColorList();
Configuration::Configs Configuration::configs = createConfigurationMap();

Configuration::Configuration()
{
}

Color Configuration::getFirstUnusedColor(Colors& usedColors)
{
    for (Colors::iterator poolIt = playerColors.begin(); poolIt != playerColors.end(); ++poolIt)
    {
        Colors::iterator usedIt = std::find(usedColors.begin(), usedColors.end(), *poolIt);
        if (usedIt == usedColors.end())
        {
            return *poolIt;
        }
    }
    return ColorGreen();
}

Colors Configuration::createColorList()
{
    Colors m;
    m.push_back(ColorGreen());
    m.push_back(ColorBlue());
    m.push_back(ColorPurple());
    m.push_back(ColorRed());
    return m;
}

void Configuration::set(Key key, std::string value)
{
    configs[key] = value;
}

std::string Configuration::get(Key key)
{
    return configs[key];
}

void Configuration::save()
{
    std::ofstream configFile;
    configFile.open("resources/config.cfg", std::ofstream::out);
    for (Configs::iterator it = configs.begin(); it != configs.end(); ++it)
    {
        configFile << it->first << " " << it->second << std::endl;
    }
}

void Configuration::load()
{
    std::ifstream configFile;
    configFile.open("resources/config.cfg", std::ofstream::in);
    std::string line;
    while(std::getline(configFile, line))
    {
        int key;
        size_t delimeterPos = line.find(" ");
        std::istringstream (line.substr(0, delimeterPos)) >> key;
        configs[(Key)key] = line.substr(delimeterPos + 1);
    }
}

Configuration::Configs Configuration::createConfigurationMap()
{
    Configs c;
    c.insert(Config(LOCAL_HOST, "127.0.0.1"));
    c.insert(Config(SERVER_IP, "127.0.0.1"));
    c.insert(Config(CLIENT_NAME, "Marcus"));
    return c;
}

